package com.gitee.ws;

import com.gitee.dto.SaveGroupChatDTO;
import com.gitee.entity.User;
import com.gitee.service.GroupService;
import com.gitee.vo.GroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
@Slf4j
public class ChatController {
    @Resource
    private GroupService groupService;

    private final SimpMessageSendingOperations messageSendingOperations;

    public ChatController(SimpMessageSendingOperations messageSendingOperations) {
        this.messageSendingOperations = messageSendingOperations;
    }

    // 收到加入消息，将消息发送给所有人，同时存储用户信息
    @MessageMapping("/chat.join")
    @SendTo("/topic/public")
    public Message join(@Payload Message message, SimpMessageHeaderAccessor headerAccessor) {
        log.info("User joined: {}", message);
        headerAccessor.getSessionAttributes().put("username", message.getSender());
        return message;
    }

    // 收到公共消息，将消息发送给所有人
    @MessageMapping("/chat.sendPublicMessage")
    @SendTo("/topic/public")
    public Message sendPublicMessage(@Payload Message message) {
        log.info("sendPublicMessage: {}", message);
        return message;
    }

    // 收到私人消息，将消息发送给指定用户，同时发送给自己
    @MessageMapping("/chat.sendPrivateMessage")
    public void sendPrivateMessage(@Payload Message message) {
        log.info("sendPrivateMessage: {}", message);
        messageSendingOperations.convertAndSendToUser(message.getReceiver(), "/private", message);
        messageSendingOperations.convertAndSendToUser(message.getSender(), "/private", message);
    }

    @MessageMapping("/chat.sendGroupMessage")
    public void sendGroupMessage(@Payload Message message) {
        log.info("sendGroupMessage: {}", message);
        // 查询数据库, 将数据响应给群聊中的所有用户
        // 1.查询该群聊有哪些用户
        GroupVO groupInfo = groupService.getGroupInfo(Integer.valueOf(message.getReceiver()));

        // 查找当前手机号的用户id
        Integer userId = 0;
        for (User user : groupInfo.getUserList()) {
            if (message.getSender().equals(user.getPhone())) {
                userId = user.getId();
            }
        }

        // 2.保存聊天记录
        SaveGroupChatDTO saveGroupChatDTO = new SaveGroupChatDTO();
        saveGroupChatDTO.setGroupId(Integer.valueOf(message.getReceiver()));
        saveGroupChatDTO.setContent(message.getContent());
        saveGroupChatDTO.setUserId(userId);
        groupService.saveGroupChat(saveGroupChatDTO);

        // 3.响应所有在群聊中的用户(自己也包含在内)
        groupInfo.getUserList().forEach(it -> messageSendingOperations.convertAndSendToUser(it.getPhone(), "/groupChat", message));


    }
}
